# 正则
import re

msg = 'Johnson, Johnnason and Johnnathan will attend my party tonight.'
pattern = 'John(son|nason|nathan)'
pattern2 = 'John((na)?son)'
pattern3 = r'\w+'  # 不限长度的单字
pattern4 = r'John\w*'  # John 开头的单字

txt = re.search(pattern, msg)
txts = re.findall(pattern, msg)  # 只会搜寻到分组中的内容(son|nason|nathan)
txt2 = re.search(pattern2, msg)
txt3 = re.findall(pattern3, msg)
txt4 = re.findall(pattern4, msg)

print('txt4: ', txt4)
print('txt3: ', txt3)
print('txt2: ', txt2.group())
print('txt2: ', txt2.end())
print('txt2: ', txt2.span())  # 搜寻到的字符串起始和结束位置

print(txts)

print(txt)
print(txt.group())
print(txt.groups())
print(txt.group(1))

'''
复杂正则练习'''

test_msg = "我喜欢看小龙女与杨过，不仅因为小龙女美丽，杨过在戏中的所扮演的角色更让我喜欢"
while True:
    target = input("请输入要搜寻的字符串：")
    s_pattern = target
    r_txt = re.findall(s_pattern, test_msg)
    if len(r_txt) > 0:
        print("已查到 %s : ,共出现 %d 次" % (target, len(r_txt)))
    else:
        print("未搜寻到 %s:" % target)
    q = input("是否继续搜寻是(y或Y)则继续，否(n或N)则结束:")
    if q == 'y' or q == 'Y':
        continue
    else:
        break
